package com.example.library.service;

import com.example.library.entity.BorrowRecord;
import com.example.library.repository.BorrowRecordRepository;
import com.example.library.entity.Book;
import com.example.library.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BorrowService {
    @Autowired
    private BorrowRecordRepository borrowRecordRepository;
    @Autowired
    private BookRepository bookRepository;

    public List<BorrowRecord> findAll() {
        return borrowRecordRepository.findAll();
    }

    @Transactional
    public BorrowRecord save(BorrowRecord record) {
        // 仅在新增借阅时校验该书是否已被借出
        if (record.getBook() != null && record.getBook().getId() != null) {
            Book book = bookRepository.findById(record.getBook().getId()).orElse(null);
            if (book == null) throw new RuntimeException("图书不存在");
            // 新增借阅时校验“已被借出”
            if (record.getId() == null) {
                if (book.getStatus() != null && book.getStatus().equals("借出")) {
                    throw new RuntimeException("该图书已被借出");
                }
                // 新增借阅时，自动将图书状态设为借出
                book.setStatus("借出");
                bookRepository.save(book);
            }
            // 归还时（returnDate不为空），自动将图书状态设为在馆
            if (record.getReturnDate() != null) {
                book.setStatus("在馆");
                bookRepository.save(book);
            }
        }
        BorrowRecord saved = borrowRecordRepository.save(record);
        return saved;
    }

    public void deleteById(Integer id) {
        borrowRecordRepository.deleteById(id);
    }

    public List<BorrowRecord> findByUserId(Integer userId) {
        return borrowRecordRepository.findByUserId(userId);
    }
}
